import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';

import NineImage from '../../components/NineImage';
import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import ProcessTitle from '../../components/processStep/processTitle';
import ProcessStatus from '../../components/processStep/processStatus';
import { CompleteButton, PassButton } from '../../components/processStep/processButton';
import { getUserProgressStepApi, setUserProgressStepStatusApi } from '../../api/myself';

import '../user-study-time/index.scss';

const UserSubjectPass: React.FC = () => {
  const firstLoadRef = useRef<boolean>(false);
  const [userStep, setUserStep] = useState<any>({
    id: 0, 
    name: "", 
    status: 0, 
    completed_time: "", 
    children: []
  });
  const { setCarSubjectStepProcessStatus } = useAppContext();
  const [showTextContent, setShowTextContent] = useState('image');
  const stepId: number = Number(Taro.getCurrentInstance().router?.params?.stepId || '7');

  const getInitInfoData = async () => {
    try {
      const res = await getUserProgressStepApi(stepId);
      if (res.code === 200 && res.data.length === 1) {
        const result = res.data[0];
        setUserStep({
          id: stepId,
          name: result.name,
          status: result.status,
          completed_time: result.created_at,
          children: result.children?.split(',') || [],
        });
      }
    } catch (err) {
      console.log(err);
      Taro.showToast({
        title: '获取用户进度失败',
        icon: 'none'
      });
    }
  };

  const updateStepStatus = async () => {
    try {
      const res = await setUserProgressStepStatusApi(Number(stepId), 1);
      if (res.code === 200) {
        setUserStep({
          ...userStep,
          status: 2
        });
        Taro.showToast({
          title: '已完成考试成绩查询~',
          icon: 'success'
        });
        setCarSubjectStepProcessStatus(Number(stepId), 1);
      }
    } catch (err) {
      console.log(err);
      Taro.showToast({
        title: '考试成绩查询失败，请稍后重试~',
        icon: 'none'
      });
    }
  };

  useEffect(() => {
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfoData();
    }
  }, []);

  return (
    <View className="page-container  tttdyotimener">
      <PageHeader title={userStep.name} />
      {userStep.completed_time && (
        <ProcessStatus title={userStep.name} createTime={userStep.completed_time} />
      )}
      
      <View className="content-wrapper">
        <View className="main-card">
          <ProcessTitle 
            content="确认考试成绩"
            showTextContent={showTextContent} 
            setShowTextContent={setShowTextContent} />
          <View className="study-time-steps">
            {showTextContent === 'image' && (
              <NineImage images={null} stepId={stepId} />
            )}
            {showTextContent === 'text' && (
              <ScrollView scrollY>
                <View className="steps-list">
                  <View className="step-item">
                    <Text className="step-time-number">1</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>打开<Text className="importance-text">交管12123APP</Text></View>
                        <View>找到<Text className="importance-text">网办进度</Text></View>
                      </View>
                    </View>
                  </View>
                
                  <View className="step-item">
                    <Text className="step-time-number">2</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>打开<Text className="importance-text">全部</Text></View>
                        <View>找到
                          <MaterialIcons name="event" color="#4F9CE0" className="calendar-icon" size={16} />
                          <Text className="importance-text">全部</Text>
                        </View>
                      </View>
                    </View>
                  </View>
                
                  <View className="step-item">
                    <Text className="step-time-number">3</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>成绩合格</View>
                      </View>
                    </View>
                  </View>
                </View>
              </ScrollView>
            )}
          </View>
          
          <View className="button-container">
            {userStep.status === 0 ? (
              <CompleteButton onClick={updateStepStatus} content="完成考试成绩查询"/>
            ) : (
              <PassButton 
                onClick={() => Taro.navigateTo({ url: `/pages/user-car-license/index` })}
                content="请上传成绩，领取积分~"
                subText="考试通过，太棒啦！"
              />
            )}
          </View>
          
          {/* 特别注意 */}
          {stepId === 11 && (
            <View className="study-time-notice">
              <View className="notice-title">
                <MaterialIcons name="info" color="#e6a23c" className="info-icon" size={16} />
                <Text className="notice-title-text text-lg">特别注意</Text>
              </View>
              <View className="notice-content">
                <View className="text-md red-color">科二考试通过，可以刷科四学时了。</View>
              </View>
            </View>
          )}
        </View>
      </View>
    </View>
  );
};

export default UserSubjectPass;